package org.zxl.iotest.netty.test1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerInboundHandler2 extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ServerInboundHandler2.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //客户端连接成功时收到此事件
        logger.info("server channel active... ;id="+ctx.channel().id());

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "utf-8");
        String response = "ServerInboundHandler2：" + body ;
        logger.info(response);
        System.out.println("2.read");
//        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//        ctx.write(Unpooled.copiedBuffer(response.getBytes()));
        // future完成后触发监听器, 此处是写完即关闭(短连接). 因此需要关闭连接时, 要通过server端关闭. 直接关闭用方法ctx[.channel()].close()
        //.addListener(ChannelFutureListener.CLOSE);


        //使用ctx.writeAndFlush
//        ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//        ctx.channel().writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
        ctx.pipeline().writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));

//        if("hi".equals(body)){
//            //跳过ServerInboundHandler2，直接出站
//            ctx.writeAndFlush(Unpooled.copiedBuffer(response.getBytes()));
//        }else{
//            //进入下一个InboundHandler
//            ByteBuf byteBuf = Unpooled.copiedBuffer(response.getBytes());
//            ReferenceCountUtil.release(msg); //释放msg
//            ctx.fireChannelRead(byteBuf);
//        }
    }

    //channelRead完成后触发
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx)
            throws Exception {
        logger.info("读完了");
        ctx.flush();
    }

    //出错时触发
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable t)
            throws Exception {
        logger.error("server2 error:{}", t.getMessage());
        ctx.close();
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        logger.info("写完了");
    }
}
